import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.DubboShutdownHook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * 注意：此方法不要配置以下配置，graceful会立即拦截新请求，微服务模式，网关和其他服务无法及时刷新服务列表，会导致新请求全部都失败，除非做故障转移，否则无法解决此问题：
 *  server.shutdown = graceful #服务停服模式
 *  spring.lifecycle.timeout-per-shutdown-phase = 60s #服务停服最大等待时间，当存在执行的线程时，服务会等待线程执行结束再停服
 */
@Slf4j
@Component
public class ShutDownApplicationRunConfig implements ApplicationRunner {
    @Autowired
    private NacosAutoServiceRegistration nacosAutoServiceRegistration;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        Thread shutdown = new Thread(()->{
            log.info(">>>>>>>>>>>>接受到kill命令啦,开始注销nacos注册");
            nacosAutoServiceRegistration.destroy();
            log.info(">>>>>>>>>>>>注销nacos注册成功");
        });
        Runtime.getRuntime().addShutdownHook(shutdown);
    }
}